#!/usr/bin/python
# -*- coding: iso-8859-15 -*-

import pg

class DBAccess:
	def __init__(self,dbname="template1", host="localhost", port=5432, user="", passwd=""):
		self.dbname = dbname
		self.host   = host
		self.port   = port
		self.user   = user
		self.passwd = passwd
		self.connectionObject=None
	
	def __connect(self):
		try:
			self.connectionObject = pg.DB(dbname=self.dbname, host=self.host, port=self.port, user =self.user,passwd=self.passwd)
		except TypeError:
			print "bad argument type, or too many arguments, connexion echou�e"
		except SyntaxError:
			print "duplicate argument definition, connexion echou�e"
		except pg.InternalError:
 			print "some error occurred during pg connection definition, connexion echou�e"
	
	def __disconnect(self):
		try:
			if(self.connectionObject):
				self.connectionObject.close();
		except TypeError:
			print "too many (any) arguments"
		
	def executeQuery(self,text):
		self.__connect()
		try:
			result = self.connectionObject.query(text)
		except TypeError:	
			print "bad argument type, or too many arguments"
		except ValueError:
			print "empty SQL query or lost connection"
		except pg.ProgrammingError:
 			print "error in query"
		except pg.InternalError:
 			print "error during query processing"
		else:
			return result
		finally:
			self.__disconnect()
	
	def insert(self,table,dictionnaire):
		self.__connect()
		try:
			self.connectionObject.insert(table,dictionnaire)
		except TypeError:
			print 'invalid connection, bad argument type, or too many arguments'
		except MemoryError:
			print 'insert buffer could not be allocated'
		except ValueError:
			print 'unsupported values'
		else:
			print 'insertion effectuee'
		finally:
			self.__disconnect()

	def update(self,table,dictionnaire):
		self.__connect()
		try:
			self.connectionObject.update(table,dictionnaire)
		except TypeError:
			print 'invalid connection, bad argument type, or too many arguments'
		except MemoryError:
			print 'insert buffer could not be allocated'
		except ValueError:
			print 'unsupported values'
		else:
			print 'mise a jour effectuee'
		finally:
			self.__disconnect()
	
	def getTable(self):
		self.__connect()
		
		dico = self.connectionObject.get_tables()
		
		self.__disconnect()
		return dico
	
	def getAttNameForTable(self,tablename):
		self.__connect()
		
		dico = self.connectionObject.get_attnames(tablename)
		
		self.__disconnect()
		return dico